import { Context } from "koa";
import { resp } from "../utils/res";
import { cateInfo } from "../models/type";
import { newsInfo } from "../models/news";
import { pageFilter } from "../utils/pageFilter";
import { validate } from "../utils/validate";
import { Rules } from "async-validator";
import moment from "moment";
class newsData {
  async modeflag(ctx: Context) {
    resp.success(ctx, 6661);
  }

  async getCateData(ctx: Context) {
    type RES = {
      _id: string;
      cate: string;
    }[];
    try {
      let res = await cateInfo.find<RES>({}, { __v: 0 });
      let s = JSON.parse(JSON.stringify(res));

      let white = [""];
      let narr = [];
      for (let e of s) {
        if (!white.includes(e.cate)) {
          narr.push(e);
        }
      }
      if (res) {
        resp.success(ctx, narr);
      }
    } catch (error: any) {
      return resp.error(ctx, error);
    }
  }
  async getSearchData(ctx: Context) {
    const rules: Rules = {
      iptvalue: [
        {
          type: "string",
          required: true,
          message: "输入内容不能为空",
        },
      ],
      limit: [
        {
          type: "boolean",
        },
      ],
    };
    type IPT = {
      iptvalue: string;
      limit?: boolean;
    };
    const { data, error } = await validate<IPT>(ctx, rules);
    if (error) {
      return resp.error(ctx, error);
    }
    
    let searchRes = await newsInfo
      .find({ title: new RegExp(data.iptvalue, "i") })
      .limit(data.limit == true ? 100000 : 10);
    if (searchRes) {
      resp.success(ctx, searchRes);
    } else {
      resp.error(ctx, "无相关数据");
    }
  }
  async getXinWenData(ctx: Context) {
    type RES = {
      _id: string;
      cate: string;
    };
    const id = ctx.request.body.id;
    const pageSize = ctx.request.body.pageSize;
    const pageNumber = ctx.request.body.pageNumber;
    try {
      let cateRes;
      if (!id) {
        cateRes = await cateInfo.findOne<RES>({ cate: "新闻" });
      }
      let xinwenDatas = await newsInfo.find({
        cate: id || (cateRes as RES)?._id,
      });
      let rank5 = await newsInfo
        .find({
          cate: id || (cateRes as RES)?._id,
          // time: new RegExp(moment(new Date()).add(0,'year').format("YYYY-MM-DD"), "i"),
        })
        .sort({ hotRate: -1 })
        .limit(5);
      let filterRes = pageFilter(xinwenDatas, pageSize, pageNumber);
      resp.success(ctx, { hot: rank5, all: filterRes });
    } catch (error: any) {
      console.log(error);

      return resp.error(ctx, error);
    }
  }
}
const getnewsData = new newsData();
export { getnewsData };
